package com.buildings.activity;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.buildings.R;
import com.buildings.activity.reinforce.CheckUtils;
import com.buildings.api.Api;
import com.buildings.api.Constant;
import com.buildings.base.BaseActivity;
import com.buildings.bean.AddressBean;
import com.buildings.bean.BaseBean;
import com.buildings.bean.DivisionResultBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.JsonBuilder;
import com.buildings.http.MyHttpClient;
import com.buildings.util.Base64Test;
import com.buildings.util.CustomToast;
import com.buildings.util.DataUtils;
import com.buildings.util.DialogUtils;
import com.buildings.util.FormDataUtil;
import com.buildings.util.PickViewUtil;
import com.buildings.util.Utils;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String AREA = "area";

    private EditText etName;
    private EditText etNumber;
    private TextView etProvince;
    private TextView etCity;
    private TextView etXian;
    private LinearLayout etXianLayout;
    private EditText etCompany;
    private EditText etPassword;
    private EditText etPasswordAgain;
    private EditText etPhone;
    private EditText etCode;
    private Button btnCode;
    private Button btnRegister;

    private String divisionId;

    private List<DivisionResultBean.Division> provinceList;
    private List<DivisionResultBean.Division> cityList;
    public List<DivisionResultBean.Division> areaList;
    private DivisionResultBean.Division province;
    private DivisionResultBean.Division city;

    private ArrayList<AddressBean> options1Items = new ArrayList<>(); //省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();//区
    private TimeCount time;

    private Dialog myDialog;

    private EditText mUserType;//新增用户类型

    private String mSelectUserType="0";//默认为0房屋采集用户

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        time = new TimeCount(60000, 1000);
        initView();
        initJsonData();
    }

    private void initView(){
        findViewById(R.id.iv_back).setOnClickListener(this);
        etName = findViewById(R.id.et_name);
        etNumber = findViewById(R.id.et_number);
        etProvince = findViewById(R.id.et_province);
        etProvince.setOnClickListener(this);
        etCity = findViewById(R.id.et_city);
        etXian = findViewById(R.id.et_xian);
        etXianLayout = findViewById(R.id.ll_xian_layout);
        etCity.setOnClickListener(this);
        etXian.setOnClickListener(this);
        etCompany = findViewById(R.id.et_company);
        etPassword = findViewById(R.id.et_password);
        etPasswordAgain = findViewById(R.id.et_password_again);
        etPhone = findViewById(R.id.et_phone);
        etCode = findViewById(R.id.et_code);

        btnCode = findViewById(R.id.btn_code);
        btnCode.setOnClickListener(this);
        btnRegister = findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(this);
        tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("新用户注册");

        mUserType = findViewById(R.id.et_user_type);
        mUserType.setOnClickListener(this);
        mUserType.setText("房屋数据采集用户");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.et_province:
                Utils.hintKb(activity);

                getDivisions("root",PROVINCE,"",null);

                //{"divisionId":"0","divisionCode":null,"divisionName":"0a","parentId":null,"allParentId":null,"level":null,"divisionType":null,"region":null,"isValid":null,"createUser":null,"createTime":null,"updateUser":null,"updateTime":null}
                break;
            case R.id.et_city:
                if(TextUtils.isEmpty(etProvince.getText().toString())){
                    CustomToast.showToast(activity, "请先选择省");
                    return;
                }

                getDivisions(province.getDivisionId(),CITY,province.getDivisionType(),province);
                break;
            case R.id.et_xian:
                if(city==null){
                    CustomToast.showToast(activity, "请先选择市");
                    return;
                }
                //省市区
                getDivisions(city.getDivisionId(), RegisterActivity.AREA,"",null);
                break;
            case R.id.btn_code:
               String phone = etPhone.getText().toString();//手机号
                if (TextUtils.isEmpty(phone.trim())) {
                    lastClickTime = System.currentTimeMillis();
                    CustomToast.showToast(activity, "手机号不能为空");
                    return;
                }
                if(TextUtils.isEmpty(etPhone.getText().toString().trim()) || !checkPhone(etPhone.getText().toString().trim())){
                    CustomToast.showToast(activity,"请输入正确手机号");
                    return;
                }

                //多次点击只执行一次
                if (Math.abs(lastClickTime - System.currentTimeMillis()) < 3000) {
                    lastClickTime = 0;
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                time.start();
                break;
            case R.id.et_user_type:
                final List<String> types = FormDataUtil.userType();
                PickViewUtil.showPickerViewOne(activity, "", types,
                    new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            String type = types.get(options1);
                            mSelectUserType = String.valueOf(options1);
                            mUserType.setText(type);
                            etXianLayout.setVisibility(options1==0?View.GONE:View.VISIBLE);
                        }
                    });
                break;
            case R.id.btn_register:

                if(TextUtils.isEmpty(etName.getText().toString())){
                    CustomToast.showToast(activity,"请输入姓名");
                    return;
                }
                if(TextUtils.isEmpty(etNumber.getText().toString()) || !checkCardNumber(etNumber.getText().toString())){
                    CustomToast.showToast(activity,"请输入正确身份证");
                    return;
                }
//                if(etNumber.getText().toString().length() != 18){
//                    CustomToast.showToast(activity,"请输入正确身份证");
//                    return;
//                }

                if(TextUtils.isEmpty(etProvince.getText().toString())){
                    CustomToast.showToast(activity,"请输入省");
                    return;
                }
                if(TextUtils.isEmpty(etCity.getText().toString())){
                    CustomToast.showToast(activity,"请输入市");
                    return;
                }
                if (!"0".equals(mSelectUserType)) {
                    if (TextUtils.isEmpty(etXian.getText().toString())) {
                        CustomToast.showToast(activity, "请输入区县");
                        return;
                    }
                }
                if(TextUtils.isEmpty(etPassword.getText().toString())){
                    CustomToast.showToast(activity,"请输入密码");
                    return;
                }
                if(TextUtils.isEmpty(etPasswordAgain.getText().toString())){
                    CustomToast.showToast(activity,"请输入确认密码");
                    return;
                }
                if(etPassword.getText().toString().length() < 6 || etPassword.getText().toString().length() >12){
                    CustomToast.showToast(activity,"密码长度为6-12位");
                    return;
                }
//                if(!checkPassword(etPassword.getText().toString())){
//                    CustomToast.showToast(activity,"密码必须包含数字和字母");
//                    return;
//                }
                if(!TextUtils.equals(etPassword.getText().toString(),etPasswordAgain.getText().toString())){
                    CustomToast.showToast(activity,"两次密码输入不一致");
                    return;
                }
                if(TextUtils.isEmpty(etPhone.getText().toString())){
                    CustomToast.showToast(activity,"请输入手机号");
                    return;
                }
//                if(etPhone.getText().toString().length() != 11){
//                    CustomToast.showToast(activity,"请输入正确手机号");
//                    return;
//                }
                if(TextUtils.isEmpty(etPhone.getText().toString().trim()) || !checkPhone(etPhone.getText().toString().trim())){
                    CustomToast.showToast(activity,"请输入正确手机号");
                    return;
                }

                if (!CheckUtils.checkNullEditText(mUserType, "请选择用户类型")){
                    return;
                }
//                if(TextUtils.isEmpty(etCode.getText().toString())){
//                    CustomToast.showToast(activity,"请输入验证码");
//                    return;
//                }
                if(myDialog == null){
                    myDialog = DialogUtils.showRefreshDialog(activity);
                }else {
                    myDialog.show();
                }
                //调用注册接口
                register();
                break;
        }
    }


    private void getDivisions(String divisionid, final String type,String provinceType, DivisionResultBean.Division division) {
        //divisions/{divisionid}/subdivisions


        if(TextUtils.equals("Municipality",provinceType)){
            //省的直辖市
            if(TextUtils.equals(RegisterActivity.PROVINCE,type)){

            }else if(TextUtils.equals(RegisterActivity.CITY,type)){
                cityList = new ArrayList<>();
                if(division != null){
                    cityList.add(division);
                }
                showPickerView(cityList,RegisterActivity.CITY);
            }else if(TextUtils.equals(RegisterActivity.AREA,type)){

            }
            return;
        }


        if(myDialog == null){
            myDialog = DialogUtils.showRefreshDialog(activity);
        }else {
            myDialog.show();
        }

        String url = Api.GET_LOCATION+"divisions/"+divisionid+"/subdivisions";
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
//                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<DivisionResultBean>() {
                    @Override
                    public void onSuccess(DivisionResultBean divisionResultBean) {
                        super.onSuccess(divisionResultBean);
                        if (myDialog != null)
                            myDialog.dismiss();
                        if(divisionResultBean != null && divisionResultBean.getCode() == 200){
                            if(divisionResultBean.getData() != null){
                                if(TextUtils.equals(PROVINCE,type)){
                                    provinceList = divisionResultBean.getData();
                                    showPickerView(provinceList,PROVINCE);
                                }else if(TextUtils.equals(CITY,type)){
                                    cityList = divisionResultBean.getData();
                                    showPickerView(cityList,CITY);
                                }else if (TextUtils.equals(AREA, type)){
                                    areaList= divisionResultBean.getData();
                                    showPickerView(areaList,AREA);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        CustomToast.showToast(activity,"网络异常");

                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        CustomToast.showToast(activity,"网络异常");

                        if (myDialog != null)
                            myDialog.dismiss();
                    }
                });

    }


    private void register() {
        String password = etPassword.getText().toString();
//        String encryptStr="";
//
//        try {
//            encryptStr = LoginActivity.encryptDataStr(password.getBytes(),LoginActivity.getPublicKey(Base64Test.decode(Constant.PUBLIC_KEY)));
//        } catch (Exception e) {
//            e.printStackTrace();
//            CustomToast.showToast(activity,"密码加密报错");
//            return;
//        }
        JsonBuilder jsonBuilder = new JsonBuilder(this);
        jsonBuilder.put("relName", etName.getText().toString());
        jsonBuilder.put("idNumber", etNumber.getText().toString());
        jsonBuilder.put("userAddress", etProvince.getText().toString()+etCity.getText().toString()+etXian.getText().toString());
        jsonBuilder.put("unit", etCompany.getText().toString());
        jsonBuilder.put("pwd",password );
//        jsonBuilder.put("pwd",encryptStr );
        jsonBuilder.put("userName", etPhone.getText().toString());
        jsonBuilder.put("division", divisionId );
        jsonBuilder.put("userType", mSelectUserType );

        MyHttpClient
                .newBuilder()
                .post()
                .url(Api.REGISTER)
                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<BaseBean>() {
                    @Override
                    public void onSuccess(BaseBean bean) {
                        super.onSuccess(bean);
                        //{"code":200,"data":{"message":"注册成功,请等待管理员审核!"},"message":null}
                        if (myDialog != null)
                            myDialog.dismiss();
                        if(bean != null && bean.getCode() == 200){
                            CustomToast.showToast(activity,"注册成功,请等待管理员审核");
                            finish();
                        }else {
                            if(!TextUtils.isEmpty(bean.getMessage())){
                                CustomToast.showToast(activity,bean.getMessage());
                            }else {
                                CustomToast.showToast(activity,"注册失败");
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        CustomToast.showToast(activity,"网络异常");

                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        CustomToast.showToast(activity,"网络异常");

                        if (myDialog != null)
                            myDialog.dismiss();
                    }
                });

    }

    public boolean checkPhone(String str) {

        String regexp = "^1(3|4|5|6|7|8|9)\\d{9}$";

        Pattern pattern = Pattern.compile(regexp);

        Matcher matcher = pattern.matcher(str);

        return matcher.find();

    }
    public static boolean checkPassword(String str) {

        String regexp = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$";

        Pattern pattern = Pattern.compile(regexp);

        Matcher matcher = pattern.matcher(str);

        return matcher.find();

    }
    public boolean checkCardNumber(String str) {

        String regexp = "^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([8][1-2]))\\d{4}(([1][9]\\d{2})|([2]\\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\\d{3}[0-9xX]$";

        Pattern pattern = Pattern.compile(regexp);

        Matcher matcher = pattern.matcher(str);

        return matcher.matches();

    }

    private void GetCodeHttp() {
        JsonBuilder jsonBuilder = new JsonBuilder(this);
        jsonBuilder.put("doctorMobile", etPhone.getText().toString());
        jsonBuilder.put("flag", "A");

        MyHttpClient
                .newBuilder()
                .post()
                .url("")
                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack() {
                    @Override
                    public void onSuccess(Object o) {
                        super.onSuccess(o);

                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
//                        if (myDialog != null)
//                            myDialog.dismiss();
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
//                        if (myDialog != null)
//                            myDialog.dismiss();
                    }
                });

    }

    /* 倒计时类 */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {
            btnCode.setText("重新获取");
            btnCode.setClickable(true);

        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            btnCode.setClickable(false);
            btnCode.setText("（" + millisUntilFinished / 1000 + "s）");
        }
    }

    private void showPickerView(final List<DivisionResultBean.Division> list, final String type) {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                DivisionResultBean.Division division = list.get(options1);
                switch (type){
                    case PROVINCE:
                        province = division;
                        city = null;
                        etCity.setText("");
                        etXian.setText("");
                        etProvince.setText(division.getDivisionName());
                        break;
                    case CITY:
                        city = division;
                        etCity.setText(division.getDivisionName());
                        divisionId = division.getDivisionId();
                        break;
                    case AREA:
                        etXian.setText(division.getDivisionName());
                        break;
                }

                //返回的分别是三个级别的选中位置
//                etAddress.setText(options1Items.get(options1).getPickerViewText() + "  "
//                        + options2Items.get(options1).get(options2) );

            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);//一级选择器
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器
//        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据 （省市区三级联动）
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = DataUtils.getAddressJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<AddressBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<AddressBean> parseData(String result) {//Gson 解析
        ArrayList<AddressBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                AddressBean entity = gson.fromJson(data.optJSONObject(i).toString(), AddressBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
